import {NextRequest, NextResponse} from "next/server";
import {PrismaClient} from "@prisma/client";

interface Topic {
    userId:  string
    avatar:  string
    content: string
    images:  string
    options: string[]
}

// 创建prisma客户端对象
const prisma = new PrismaClient()

// 查询topic
export async function GET(request: NextRequest) {
    try {
        const {searchParams} = new URL(request.url)
        const userId = searchParams.get("userId") as string
        const topics = await prisma.topic.findMany({
            where: {
                userId
            },
            include: {
                options: true
            }
        })
        return NextResponse.json({topics}, {status: 200})
    }catch (e) {
        let message = "服务器发生异常："
        if (e instanceof Error) {
            message += e.message
        }else {
            message += e
        }
        return NextResponse.json({message}, {status: 500})
    }finally {
        prisma.$disconnect()
    }
}

// 新增topic
export async function POST(request: NextRequest) {
    try {
        const data = await request.json() as Topic
        const topic = await prisma.topic.create({
            data: {
                userId: data.userId,
                avatar: data.avatar,
                content: data.content,
                images: data.images,
                options: {
                    create: data.options.map(item => {
                        return {
                            key: item,
                            value: 0
                        }
                    })
                }
            },
            include: {
                options: true
            }
        })
        return NextResponse.json({topic}, {status: 200})
    }catch (e) {
        return NextResponse.json({message: "服务器发生异常"
        })
    }finally {
        prisma.$disconnect()
    }
}
